<template>
  <div id="app">
    <!-- 布局 -->
    <el-container style="height: 100vh; border: 1px solid #eee;">
      <!-- 侧边栏 -->
      <el-aside width="200px" style="background-color: #545c64;">
        <el-menu
          default-active="1"
          class="el-menu-vertical-demo"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#fff"
          @select="handleMenuSelect"
        >
          <el-menu-item index="1">
            <i class="fa fa-users"></i>
            <span>用户管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容 -->
      <el-container>
        <!-- 顶部 -->
        <el-header style="background-color: #fff; border-bottom: 1px solid #eee;">
          <div style="line-height: 60px; text-align: center; font-size: 18px; font-weight: bold; color: #333;">
            用户管理系统
          </div>
        </el-header>

        <!-- 主要内容区 -->
        <el-main style="padding: 20px; background-color: #f5f7fa;">
          <div v-if="activeView === 'users'">
            <el-card style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
              <!-- 标题与按钮 -->
              <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0; color: #333;">用户列表</h2>
                <el-button type="primary" @click="showAddUserDialog = true">
                  <i class="fa fa-plus"></i> 添加用户
                </el-button>
              </div>

              <!-- 用户表格 -->
              <el-table :data="users" border style="width: 100%; background-color: #fff;">
                <el-table-column prop="id" label="ID" width="80"></el-table-column>
                <el-table-column label="头像" width="100">
                  <template #default="scope">
                    <el-avatar :src="getAvatarUrl(scope.row.avatar)" size="large">
                      <i v-if="!scope.row.avatar" class="fa fa-user"></i>
                    </el-avatar>
                  </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="created_at" label="创建时间"></el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showAddUserDialog"
      width="500px"
      :modal="true"
    >
      <el-form :model="formData" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" required>
          <el-input v-model="formData.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5000/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarUploadSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-avatar :src="formData.avatar ? getAvatarUrl(formData.avatar) : ''" size="large" style="border: 1px dashed #ddd;">
              <i v-if="!formData.avatar" class="fa fa-plus"></i>
            </el-avatar>
          </el-upload>
          <div class="el-upload__tip" style="margin-top: 10px;">
            支持jpg、png格式，文件大小不超过2MB
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddUserDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, toRefs } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElNotification } from 'element-plus'

// 1. 定义响应式状态（核心数据）
const state = reactive({
  activeView: 'users',          // 当前激活的视图
  users: [],                    // 用户列表
  showAddUserDialog: false,     // 控制弹窗显示
  formData: {                   // 表单数据
    id: null,
    username: '',
    email: '',
    avatar: ''
  },
  dialogTitle: '添加用户',      // 弹窗标题
})

// 2. 方法定义
// 切换菜单
const handleMenuSelect = (index) => {
  state.activeView = index === '1' ? 'users' : 'users'
}

// 获取用户列表
const fetchUsers = () => {
  axios.get('http://localhost:5000/api/users')
    .then(res => { state.users = res.data })
    .catch(err => {
      showNotification('错误', '获取用户列表失败', 'error')
      console.error(err)
    })
}

// 获取头像URL
const getAvatarUrl = (avatar) => {
  return avatar ? `http://localhost:5000/uploads/${avatar}` : ''
}

// 显示通知（编程式调用，修复警告）
const showNotification = (title, message, type) => {
  ElNotification({
    title,
    message,
    type,
    duration: 3000,
  })
}

// 编辑用户
const handleEdit = (row) => {
  state.formData = { ...row }
  state.dialogTitle = '编辑用户'
  state.showAddUserDialog = true
}

// 删除用户
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除这个用户吗？',
    '确认删除',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    axios.delete(`http://localhost:5000/api/users/${id}`)
      .then(() => {
        showNotification('成功', '用户已删除', 'success')
        fetchUsers()
      })
      .catch(err => {
        showNotification('错误', '删除用户失败', 'error')
        console.error(err)
      })
  }).catch(() => { /* 取消删除 */ })
}

// 提交表单（新增/编辑）
const submitUserForm = () => {
  // 简单校验
  if (!state.formData.username.trim()) {
    return showNotification('警告', '用户名不能为空', 'warning')
  }
  if (!state.formData.email.trim()) {
    return showNotification('警告', '邮箱不能为空', 'warning')
  }

  // 判断是新增还是编辑
  const request = state.formData.id
    ? axios.put(`http://localhost:5000/api/users/${state.formData.id}`, state.formData)
    : axios.post('http://localhost:5000/api/users', state.formData)

  request.then(() => {
    const msg = state.formData.id ? '用户信息已更新' : '用户已创建'
    showNotification('成功', msg, 'success')
    state.showAddUserDialog = false
    fetchUsers()
  }).catch(err => {
    const msg = state.formData.id ? '更新用户信息失败' : '创建用户失败'
    showNotification('错误', msg, 'error')
    console.error(err)
  })
}

// 头像上传成功
const handleAvatarUploadSuccess = (res) => {
  state.formData.avatar = res.unique_name
  showNotification('成功', '头像上传成功', 'success')
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) showNotification('错误', '仅支持 JPG/PNG 格式', 'error')
  if (!isLt2M) showNotification('错误', '文件大小不能超过 2MB', 'error')
  return isJPG && isLt2M
}

// 3. 生命周期
onMounted(() => {
  fetchUsers() // 初始化加载用户列表
})

// 4. 监听弹窗关闭
watch(() => state.showAddUserDialog, (newVal) => {
  if (!newVal) {
    state.formData = { id: null, username: '', email: '', avatar: '' }
    state.dialogTitle = '添加用户'
  }
})

// 5. 暴露给模板
const {
  activeView,
  users,
  showAddUserDialog,
  formData,
  dialogTitle,
} = toRefs(state)

</script>

<style scoped>
/* 保持您偏好的颜色风格 */
.el-menu-vertical-demo {
  background-color: #545c64 !important;
}
.el-menu-item.is-active {
  background-color: #42b983 !important;
}
.el-button--primary {
  background-color: #42b983 !important;
  border-color: #42b983 !important;
}
.el-button--primary:hover {
  background-color: #359e6d !important;
  border-color: #359e6d !important;
}
.el-card__header {
  border-bottom: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}
.el-table th {
  background-color: #f5f7fa;
}
.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e8e8e8;
}
</style>
